from rest_framework import serializers
from datacenter.models import Entity, EntityField


class EntityFieldSerializer(serializers.ModelSerializer):
    value = serializers.SerializerMethodField()

    def get_value(self, instance):
        return instance.field

    class Meta:
        model = EntityField
        fields = ['field', 'label', 'value', 'source_field', 'standard_model_field']


class EntitySerializer(serializers.ModelSerializer):
    def _save_fields(self, entity_id):
        EntityField.objects.filter(entity_id=entity_id).delete()
        for field in self.fields_data:
            field['entity_id'] = entity_id
            EntityField.objects.create(**field)

    def to_internal_value(self, data):
        self.fields_data = data.pop('fields', [])
        return super().to_internal_value(data)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        fields_queryset = EntityField.objects.filter(entity_id=instance.id).order_by('id')
        ret['fields'] = EntityFieldSerializer(fields_queryset, many=True).data
        return ret

    def save(self, **kwargs):
        instance = super().save(**kwargs)
        self._save_fields(instance.id)

    class Meta:
        model = Entity
        exclude = ['created_at', 'updated_at']
